package com.jxnu.nav_search;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;
import com.jxnu.nav_search.adapters.RecyclerBaseAdapter;
import com.jxnu.nav_search.databinding.ActivityScrollingBinding;
import com.jxnu.nav_search.utils.Datasets;
import com.jxnu.nav_search.viewModels.ScrollAcViewModel;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.cursoradapter.widget.CursorAdapter;
import androidx.cursoradapter.widget.SimpleCursorAdapter;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * 只要进行的是数据的显示
 */

public class ScrollingActivity extends AppCompatActivity {

    private ActivityScrollingBinding activityScrollingBinding = null;
    private ScrollAcViewModel scrollAcViewModel = null;


    RecyclerView recyclerView;

    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityScrollingBinding = DataBindingUtil.setContentView(this, R.layout.activity_scrolling);
        scrollAcViewModel = ViewModelProviders.of(this).get(ScrollAcViewModel.class);
        initData();
    }


    private void initData() {
        setFab();
        setSearchView();
    }

    private void setFab() {
        activityScrollingBinding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }


    @SuppressLint("HandlerLeak")
    private void setRecyclerView(String query) {
        if (recyclerView == null) {
            recyclerView = findViewById(R.id.rv_show);
            recyclerView.setLayoutManager(new LinearLayoutManager(ScrollingActivity.this));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(ScrollingActivity.this,
                    DividerItemDecoration.VERTICAL);
            Drawable drawable = ContextCompat.getDrawable(ScrollingActivity.this, R.color.colorAccent);
            dividerItemDecoration.setDrawable(drawable);
            recyclerView.addItemDecoration(dividerItemDecoration);
            //使用handler进行跟新视图
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    Bundle bundle = msg.getData();
                    List<Datasets> list = bundle.getParcelableArrayList("datapar");
                    recyclerView.setAdapter(new RecyclerBaseAdapter(list, R.layout.fragment_list));
                }
            };
        }


        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Datasets> list = null;
                try {
                    list = scrollAcViewModel.getQuery(query);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                System.out.println("_______---===============");
                System.out.println(list);

                Message msg = new Message();
                Bundle bundle = new Bundle();

                bundle.putParcelableArrayList("datapar", (ArrayList<? extends Parcelable>) list);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        }).start();
    }

    private void setSearchView() {
        /**
         *设置建议搜素的内容
         */

        final Cursor cursor = scrollAcViewModel.getSuggestion(this);

        /**
         *设置建议搜素的内容
         */
        final SearchView searchBar = activityScrollingBinding.searchBar;

        searchBar.setQueryHint("请输入搜素内容...");

        searchBar.setSubmitButtonEnabled(true);

        searchBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(ScrollingActivity.this, query, Toast.LENGTH_SHORT).show();
                setRecyclerView(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                //设置建议
                searchBar.setSuggestionsAdapter(new SimpleCursorAdapter(ScrollingActivity.this, R.layout.layout_item, cursor, new String[]{"name"},
                        new int[]{R.id.textView}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER));
                setRecyclerView(newText);
                Toast.makeText(ScrollingActivity.this, newText, Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        searchBar.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Toast.makeText(ScrollingActivity.this, "" + hasFocus, Toast.LENGTH_SHORT).show();
            }
        });


        searchBar.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
            @Override
            public boolean onSuggestionSelect(int position) {
//                Toast.makeText(ScrollingActivity.this, "" + position, Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onSuggestionClick(int position) {

                cursor.moveToPosition(position);

                Toast.makeText(ScrollingActivity.this, "" + cursor.getString(1), Toast.LENGTH_SHORT).show();
                return false;
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

